/*****************************************************
*                                                                          
*               COPYRIGHT (c) 2015-2017 Hargic Corporation              
*                         All Rights Reserved                              
*                                                                          
* The source code contained or described herein and all documents          
* related to the source code ("Material") are owned by Hargic         
* Corporation or its licensors.  Title to the Material remains             
* with Hargic Corporation or its suppliers and licensors.               
*                                                                          
* The Material is protected by worldwide copyright and trade secret        
* laws and treaty provisions. No part of the Material may be used,         
* copied, reproduced, modified, published, uploaded, posted, transmitted,  
* distributed, or disclosed in any way except in accordance with the       
* applicable license agreement.                                            
*                                                                          
* No license under any patent, copyright, trade secret or other            
* intellectual property right is granted to or conferred upon you by       
* disclosure or delivery of the Materials, either expressly, by            
* implication, inducement, estoppel, except in accordance with the         
* applicable license agreement.                                            
*                                                                          
* Unless otherwise agreed by Hargic in writing, you may not remove or   
* alter this notice or any other notice embedded in Materials by Hargic 
* or Hargic's suppliers or licensors in any way.                        
*                                                                          
** Author: ted.huang
** Date: 2018-02-25
*
*****************************************************/

/***** Include files ********************************/
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include "spi_if.h"
#include "sx1278.h"
#include "protocol.h"
#include "msg_handler.h"


/***** Defines **************************************/

/***** Define structure *****************************/

/***** Define constant ******************************/

/***** Define global ********************************/

/***** Define Prototype of functions ****************/
static void spi_write_byte(unsigned char value);
static unsigned char spi_read_byte(void);
void sx1278_handler(void);
void sx1278_send(unsigned char *pbuf, unsigned int len);


/**
 * @brief
 * @param  None
 * @retval None
 */
int main(int argc, char **argv)
{
	lpCtrlTypefunc_t func;
	unsigned char value, i;
    int dev, status, sendlen;
    msg_type_led_t led;

	if (spi_init() != 0)
    {
		printf("spi init failed.\n");
		return -1;
    }

    if (sx1278_gpio_init() != 0)
    {
    	printf("gpio init failed.\n");
    	return -2;
    }

    func.lpByteWritefunc = spi_write_byte;
    func.lpByteReadfunc = spi_read_byte;
    register_rf_func(&func);

    SX1276Reset();
    SX1276LORA_INT();
    printf("after init.\n");
    for (i=0; i<=0x1e; i++)
    {
    	value = SX1276ReadBuffer(i);
    	printf("read REG %02x: %02x\n", i, value);
    }

    while (1)
    {
        // sx1278_handler();

        printf("input device number: ");
        scanf("%d", &dev);

        printf("input status: ");
        scanf("%d", &status);

        led.status = status;
        sendlen = msg_send_led_req(&led);
        sx1278_send(send_buffer, sendlen);

        // sx1278_send_test(dev, status);
        printf("device %d, status %s\n", dev, status ? "on" : "off");

        // sx1278_send_test(3, 1);
        // printf("device %d, status %s\n", 3, "on");
        // sleep(3);

        // sx1278_send_test(3, 0);
        // printf("device %d, status %s\n", 3, "off");
        // sleep(3);

        // sx1278_send_test(2, 1);
        // printf("device %d, status %s\n", 2, "on");
        // sleep(3);

        // sx1278_send_test(2, 0);
        // printf("device %d, status %s\n", 2, "off");
        // sleep(3);

        // sx1278_send_test(4, 1);
        // printf("device %d, status %s\n", 4, "on");
        // sleep(3);

        // sx1278_send_test(4, 0);
        // printf("device %d, status %s\n", 4, "off");
        // sleep(3);
    }

    spi_de_init();
    return 0;
}

void sx1278_handler(void)
{
    static int cnt = 0;
    unsigned char RF_REC_RLEN_i = 0;
    unsigned char recv[30];

    RF_EX0_STATUS = SX1276ReadBuffer( REG_LR_IRQFLAGS);
    // printf("recv flag %02x\n", RF_EX0_STATUS);
    if (RF_EX0_STATUS > 0) 
    {
        if ((RF_EX0_STATUS & 0x40) == 0x40) 
        {
            //GPIO_OUTPUT_SET(GPIO_ID_PIN(2),0);
            CRC_Value = SX1276ReadBuffer( REG_LR_MODEMCONFIG2);
            // printf("get CRC_Value %x\n", CRC_Value);
            if ((CRC_Value & 0x04) == 0x04) 
            {
                SX1276WriteBuffer(REG_LR_FIFOADDRPTR, 0x00);
                SX1278_RLEN = SX1276ReadBuffer(REG_LR_NBRXBYTES);
                // uartSendString("recvieve data num=%d\r\n",SX1278_RLEN);
                
                // lpTypefunc.lpSwitchEnStatus(enOpen);
                spi_nss_enable();
                
                // read fifo register (0x00)
                // lpTypefunc.lpByteWritefunc(0x00);
                for (RF_REC_RLEN_i = 0; RF_REC_RLEN_i < SX1278_RLEN; RF_REC_RLEN_i++) 
                {
                    recv[RF_REC_RLEN_i] = lpTypefunc.lpByteReadfunc();
                }
                
                // lpTypefunc.lpSwitchEnStatus(enClose);
                spi_nss_disable();

                recv[RF_REC_RLEN_i] = '\0';
                printf("[%d]recieved: %s\n", ++cnt, recv);
                // if(strncmp((char *)recv, "ai-thinker", 10) == 0)
                // {
                //     printf("recieved: %s\n", recv);
                // }
            }
            // lpTypefunc.lpRecvDataTousr(recv,SX1278_RLEN);
            SX1276LoRaSetOpMode(Stdby_mode);
            SX1276WriteBuffer(REG_LR_IRQFLAGSMASK, IRQN_RXD_Value);     //´ò¿ª·¢ËÍÖÐ¶Ï
            SX1276WriteBuffer(REG_LR_HOPPERIOD, PACKET_MIAX_Value);
            SX1276WriteBuffer( REG_LR_DIOMAPPING1, 0x00);
            SX1276WriteBuffer( REG_LR_DIOMAPPING2, 0x00);
            SX1276LoRaSetOpMode(Receiver_mode);
            // lpTypefunc.paSwitchCmdfunc(rxOpen);
        } 
        else if ((RF_EX0_STATUS & 0x08) == 0x08) 
        {
            SX1276LoRaSetOpMode(Stdby_mode);
            SX1276WriteBuffer(REG_LR_IRQFLAGSMASK, IRQN_RXD_Value); //´ò¿ª·¢ËÍÖÐ¶Ï
            SX1276WriteBuffer(REG_LR_HOPPERIOD, PACKET_MIAX_Value);
            SX1276WriteBuffer( REG_LR_DIOMAPPING1, 0x00);
            SX1276WriteBuffer( REG_LR_DIOMAPPING2, 0x00);
            SX1276LoRaSetOpMode(Receiver_mode);
            // lpTypefunc.paSwitchCmdfunc(rxOpen);
        } 
        else if ((RF_EX0_STATUS & 0x04) == 0x04) 
        {
            if ((RF_EX0_STATUS & 0x01) == 0x01)     //±íÊ¾CAD ¼ì²âµ½À©ÆµÐÅºÅ Ä£¿é½øÈëÁË½ÓÊÕ×´Ì¬À´½ÓÊÕÊý¾Ý
            { 
                SX1276LoRaSetOpMode(Stdby_mode);
                SX1276WriteBuffer(REG_LR_IRQFLAGSMASK, IRQN_RXD_Value); //´ò¿ª·¢ËÍÖÐ¶Ï
                SX1276WriteBuffer(REG_LR_HOPPERIOD, PACKET_MIAX_Value);
                SX1276WriteBuffer( REG_LR_DIOMAPPING1, 0x02);
                SX1276WriteBuffer( REG_LR_DIOMAPPING2, 0x00);
                SX1276LoRaSetOpMode(Receiver_mode);
                // lpTypefunc.paSwitchCmdfunc(rxOpen);
            } 
            else
            {                          
                SX1276LoRaSetOpMode(Stdby_mode);
                SX1276WriteBuffer(REG_LR_IRQFLAGSMASK, IRQN_SEELP_Value);   //´ò¿ª·¢ËÍÖÐ¶Ï
                SX1276WriteBuffer( REG_LR_DIOMAPPING1, 0x00);
                SX1276WriteBuffer( REG_LR_DIOMAPPING2, 0x00);
                SX1276LoRaSetOpMode(Sleep_mode);
                //PA_SEELP_OUT();
            }
        } 
        else 
        {
            SX1276LoRaSetOpMode(Stdby_mode);
            SX1276WriteBuffer(REG_LR_IRQFLAGSMASK, IRQN_RXD_Value);  //´ò¿ª·¢ËÍÖÐ¶Ï
            SX1276WriteBuffer(REG_LR_HOPPERIOD, PACKET_MIAX_Value);
            SX1276WriteBuffer( REG_LR_DIOMAPPING1, 0x02);
            SX1276WriteBuffer( REG_LR_DIOMAPPING2, 0x00);
            SX1276LoRaSetOpMode(Receiver_mode);
            // lpTypefunc.paSwitchCmdfunc(rxOpen);
        }

        RF_REC_RLEN_i = 0;
        SX1276WriteBuffer( REG_LR_IRQFLAGS, 0xff);
        usleep(300 * 1000);
    }
}

void sx1278_send(unsigned char *pbuf, unsigned int len)
{
    SX1276WriteBuffer( REG_LR_IRQFLAGS, 0xff);

    FUN_RF_SENDPACKET(pbuf, len);
    usleep(10*1000);
    SX1276WriteBuffer( REG_LR_IRQFLAGS, 0xff);
}

static void spi_write_byte(unsigned char value)
{
	spi_transfer(value);
}

static unsigned char spi_read_byte(void)
{
	return spi_transfer(0xff);
}

// int main(int argc, char **argv)
// {
//     if (spi_init() != 0)
//     {
// 		printf("spi init failed.\n");
// 		return -1;
//     }
    
//     // Send a byte to the slave and simultaneously read a byte back from the slave
//     // If you tie MISO to MOSI, you should read back what was sent
//     uint8_t send_data = 0x23;
//     uint8_t read_data = spi_transfer(send_data);
//     printf("Sent to SPI: 0x%02X. Read back from SPI: 0x%02X.\n", send_data, read_data);
//     if (send_data != read_data)
// 		printf("Do you have the loopback from MOSI to MISO connected?\n");

// 	char txbuf[10];
// 	char rxbuf[10];
// 	int i;

// 	for (i=0; i<10; i++)
// 	{
// 		txbuf[i] = i;
// 		rxbuf[i] = 0;
// 	}

// 	printf("Before spi transfer.\n");
// 	printf("txbuf:");
// 	for (i=0; i<10; i++)
// 		printf(" %d", txbuf[i]);
// 	printf("\n");

// 	printf("rxbuf:");
// 	for (i=0; i<10; i++)
// 		printf(" %d", rxbuf[i]);
// 	printf("\n");

// 	// do transfer
// 	spi_transfernb(txbuf, rxbuf, 10);

// 	printf("After spi transfer.\n");
// 	printf("txbuf:");
// 	for (i=0; i<10; i++)
// 		printf(" %d", txbuf[i]);
// 	printf("\n");

// 	printf("rxbuf:");
// 	for (i=0; i<10; i++)
// 		printf(" %d", rxbuf[i]);
// 	printf("\n");
    
//     spi_de_init();
//     return 0;
// }

/* End of file */



